package cn.stylefeng.guns.modular.system.controller.ActivityUtil;

import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.impl.history.HistoryManager;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;

/**taskId ： 当前任务节点id
 * targetNodeId ：需要跳到节点
 * 退回工具类
 * @Author : xiaofei
 * @Date: 2019/8/6
 */
public class  jumpAnyWhereCmd implements Command{


       private String taskId;
       private String targetNodeId;
       private String message;


       public jumpAnyWhereCmd() {
       }

       public jumpAnyWhereCmd(String taskId, String targetNodeId,String message) {
           this.taskId = taskId;
           this.targetNodeId = targetNodeId;
           this.message =  message;
       }

       @Override
       public Object execute(CommandContext commandContext) {

           //1.获取任务实例管理类
           TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
           //2.获取当前的任务实例
           TaskEntity currentTask = taskEntityManager.findById(taskId);
           //3.获取当前节点的任务实例
           ExecutionEntity execution = currentTask.getExecution();
           String executionId = execution.getId();
           //4.获取流程id
           String processDefinitionId = execution.getProcessDefinitionId();
           //5.获取目标节点
           Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
           FlowElement flowElement = process.getFlowElement(targetNodeId);
           //6.获取历史任务管理
           HistoryManager historyManager = commandContext.getHistoryManager();
           //7.通知当前活动结束
           historyManager.recordActivityEnd(execution,message);
           //8.通知当前任务节点结束
           historyManager.recordTaskEnd(taskId,message);
           //9.删除当前的任务
           //taskEntityManager.delete(taskId);

           //10.此时设置执行实例的当前活动节点为目标节点
           execution.setCurrentFlowElement(flowElement);

           //11.向operationS中继续芽入继续流程的操作类
           commandContext.getAgenda().planContinueMultiInstanceOperation(execution);
           return null;
       }
   }




